package org.ufinity.hsms.module.device;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.achartengine.GraphicalView;
import org.json.JSONException;
import org.json.JSONObject;
import org.ufinity.hsms.R;
import org.ufinity.hsms.common.activity.BaseActivity;
import org.ufinity.hsms.common.application.HSMApplication;
import org.ufinity.hsms.common.command.AbstractCommand;
import org.ufinity.hsms.common.command.CommandService;
import org.ufinity.hsms.common.command.ICallBack;
import org.ufinity.hsms.common.utils.InfoHelper;
import org.ufinity.hsms.common.utils.StringUtils;
import org.ufinity.hsms.common.utils.chart.DrawChart;
import org.ufinity.hsms.module.device.command.HistoryCommand;
import org.ufinity.hsms.module.device.entity.HistoryEntity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

public class HistoryActivity extends BaseActivity implements OnClickListener, OnItemClickListener{
	public static final String TAG = "ItemActivity";
	private HSMApplication application;
	ProgressDialog proDialog = null;
	TextView txt_title;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	
	private int mYear_end;
	private int mMonth_end;
	private int mDay_end;

	static final int DATE_DIALOG_ID = 0;

	Button btn_date_start;
	Button btn_date_end;
	Button btn_search;
	
	List<HistoryEntity> list;
	//图表容器
	private LinearLayout linearView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		instance = this;
		application = getBaseApplication();
		application.addActivity(instance);
		setContentView(R.layout.device_table);
		initView();
		initDate();
	}
	
	
	private void initView() {
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_search.setOnClickListener(this);
		btn_date_start = (Button) findViewById(R.id.btn_date_start);
		btn_date_end = (Button) findViewById(R.id.btn_date_end);
		linearView=(LinearLayout)findViewById(R.id.chart_show);
		
		txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText(getResources().getString(R.string.items));
		proDialog = new ProgressDialog(getParent());
		proDialog.setMessage(getResources().getString(R.string.validate));
		proDialog.setIndeterminate(false);
		proDialog.setCancelable(true);
		
		
		// 获得当前时间
		Date now=new Date();
		now.getTime();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		//今天
		long timeTill = now.getTime();
		mYear_end = Integer.parseInt(simpleDateFormat.format(new Date(timeTill)).substring(0, 4));
		mMonth_end = Integer.parseInt(simpleDateFormat.format(new Date(timeTill)).substring(4, 6))-1;
		mDay_end = Integer.parseInt(simpleDateFormat.format(new Date(timeTill)).substring(6, 8));
		//昨天
		long timeFrom = timeTill - 1000L*3600*24*30;
		mYear = Integer.parseInt(simpleDateFormat.format(new Date(timeFrom)).substring(0, 4));
		mMonth = Integer.parseInt(simpleDateFormat.format(new Date(timeFrom)).substring(4, 6))-1;
		mDay = Integer.parseInt(simpleDateFormat.format(new Date(timeFrom)).substring(6, 8));
		
		//显示当前时间
		updateDisplay();
	}
	
	private void initDate() {
		if (!InfoHelper.checkNetWork(mContext)) {
			makeMyToast(mContext, getResources().getString(
					R.string.connect_error));
			return;
		}else{
			//String itemId = getIntent().getExtras().getString("itemId");
			
			Date d_start = null;
			Date d_end = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			try {
				d_start = sdf.parse(btn_date_start.getText().toString());
				d_end = sdf.parse(btn_date_end.getText().toString());
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			
			String itemId = "46224";
			HashMap<String, String> map = new HashMap<String,String>();
			map.put("itemId", itemId);
			long timeTill = d_start.getTime()/1000L;
			long timeFrom = d_end.getTime()/1000L;
			map.put("timeTill", String.valueOf(timeTill));
			map.put("timeFrom", String.valueOf(timeFrom));
			proDialog.show();
			HistoryCommand cmd = new HistoryCommand(map);
			cmd.addCallBack("history",new ICallBack<JSONObject>() {
				
				@Override
				public void callBack(AbstractCommand<JSONObject> command,
						JSONObject json, Exception ex) {
					
					Log.i("===", json.toString());
					if (json!=null && !json.isNull("result"))
					{
						String result;
						try {
							result = json.getString("result");
							list = HistoryEntity.getList(result);
							
							//显示图表
							getChartView();
							
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}else{
						makeMyToast(instance, getResources().getString(R.string.time_out));
					}
					
					if(proDialog!=null){
						proDialog.dismiss();
					}
				}
			});
			CommandService.addTaskAtFirst(cmd);
		}
	}
	
	/**
	 * 比较两个时间日期的早晚
	 * @param a
	 * @param b
	 * @return
	 */
	private boolean compare(String a,String b){
		if(StringUtils.isBlank(b)){
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
			Date now=new Date();
			b = simpleDateFormat.format(now);
		}
		if(Integer.parseInt(a)>Integer.parseInt(b)){
			return false;
		}else{
			return true;
		}
	}

	
	/**
	 * 更新显示时间
	 */
	private void updateDisplay() {
		
		btn_date_start.setText(new StringBuilder().append(mYear).append("-")
				.append(mMonth + 1).append("-")
				.append(mDay).append(" "));
		
		btn_date_end.setText(new StringBuilder().append(mYear_end).append("-")
				.append(mMonth_end + 1).append("-")
				.append(mDay_end).append(" "));
	}

	


	/**
	 * 设置开始时间
	 * @param v
	 */
	public void setStartDate(View v) {
		DatePickerDialog datePickerDialog = new DatePickerDialog(getParent(),
				mDateSetListener, mYear, mMonth, mDay);
		datePickerDialog.show();
	}
	
	/**
	 * 设置结束时间
	 * @param v
	 */
	public void setEndDate(View v) {
		DatePickerDialog datePickerDialog = new DatePickerDialog(getParent(),
				mDateSetListener_end, mYear_end, mMonth_end, mDay_end);
		datePickerDialog.show();
	}

	/**
	 * 开始时间监听
	 * @param v
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			
			if(compare(year+""+(monthOfYear<9?("0"+(monthOfYear+1)) : (monthOfYear+1))+""+(dayOfMonth<10?("0"+dayOfMonth) : dayOfMonth) , mYear_end+""+(mMonth_end<9?("0"+(mMonth_end+1)) : (mMonth_end+1))+""+(mDay_end<10?("0"+mDay_end) : mDay_end))){
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				updateDisplay();
			}else{
				makeMyToast(mContext, getResources().getString(
						R.string.time_old));
			}
		}
	};
	
	/**
	 * 结束时间监听
	 * @param v
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener_end = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			if(compare(year+""+(monthOfYear<9?("0"+(monthOfYear+1)) : (monthOfYear+1))+""+(dayOfMonth<10?("0"+dayOfMonth) : dayOfMonth),null)){
				mYear_end = year;
				mMonth_end = monthOfYear;
				mDay_end = dayOfMonth;
				updateDisplay();
			}else{
				makeMyToast(mContext, getResources().getString(
						R.string.time_old));
			}
		}
	};
	
	/**
	* 描述:创建图表 
	* 参数 
	* 返回值 void
	* 备注
	*/
	private void getChartView()
	{
		DrawChart dc=new DrawChart(list);
		GraphicalView chartView=dc.getChartView(this);
		linearView.addView(chartView);
	}
	
	public void search(View v) {
		
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id == btn_search.getId()){
			initDate();
		}
	}
	
	@Override
	public void onBackPressed() {
		//返回上一级
		finish();
	}
	
}
